package com.athl.gulimall.product.service.impl;

import com.athl.gulimall.product.entity.AttrGroupEntity;
import com.athl.gulimall.product.service.CategoryBrandRelationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.athl.common.utils.PageUtils;
import com.athl.common.utils.Query;

import com.athl.gulimall.product.dao.CategoryDao;
import com.athl.gulimall.product.entity.CategoryEntity;
import com.athl.gulimall.product.service.CategoryService;
import org.springframework.transaction.annotation.Transactional;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {
//    @Autowired
//    private CategoryDao categoryDao;
    @Autowired
    private CategoryBrandRelationService categoryBrandRelationService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithTree() {
        //1.查出所有分类(baseMapper在这里就是categoryDao)
        List<CategoryEntity> entities = baseMapper.selectList(null);
        //2.组装成父子的树形结构

        //2.1 找到所有的一级分类（这里用到了java8新特性lambda表达式和stream）
        List<CategoryEntity> leve1Menus = entities.stream().filter(categoryEntity -> {
            return categoryEntity.getParentCid() == 0;//注意：因为只有一行：大括号和return在这里可以省略
        }).map((menu) -> {
            menu.setChildren(getChildrens(menu, entities));//查找子菜单
            return menu;
        }).sorted((menu1, menu2) -> {
            return (menu1.getSort()==null?0:menu1.getSort()) - (menu2.getSort()==null?0:menu2.getSort()); //排序
        }).collect(Collectors.toList());


        return leve1Menus;
    }

    @Override
    public void removeMenuByIds(List<Long> asList) {
        //TODO 1.检查当前删除的菜单，是否被别的地方引用
        baseMapper.deleteBatchIds(asList);
    }

    @Override
    public Long[] findCatelogPath(Long catelogId) {
        List<Long> paths = new ArrayList<>();

        List<Long> parentPath = findParentPath(catelogId, paths);
        // 逆序
        Collections.reverse(parentPath);

        return parentPath.toArray(new Long[parentPath.size()]);
    }

    /**
     * 级联更新所有的关联数据
     *
     * @param category
     */
    @Transactional
    @Override
    public void updateCascade(CategoryEntity category) {
        // 1.先更新当前表的数据
        this.updateById(category);

        //2.更新关联表中的数据
        categoryBrandRelationService.updateCategory(category.getCatId(),category.getName());

    }

    private List<Long> findParentPath(Long catelogId,List<Long> paths){
        //1.收集当前节点id
        paths.add(catelogId);
        CategoryEntity byId = this.getById(catelogId);
        // 当前节点的父节点id
        Long cId = byId.getParentCid();
        if (cId != 0){
            findParentPath(cId,paths);
        }
        return paths;
    }

    /**
     * 递归查找所有商品分类下的子分类
     *
     * @param root 当前商品分类
     * @param all  在所有商品分类下查询
     * @return
     */
    private List<CategoryEntity> getChildrens(CategoryEntity root, List<CategoryEntity> all) {
        List<CategoryEntity> children = all.stream().filter(categoryEntity -> {
            return categoryEntity.getParentCid() == root.getCatId();//过滤方法，所有商品分类的父id等于当前分类的id
        }).map(categoryEntity -> {
            categoryEntity.setChildren(getChildrens(categoryEntity, all));//递归查找子菜单
            return categoryEntity;
        }).sorted((menu1, menu2) -> {
            return (menu1.getSort()==null?0:menu1.getSort()) - (menu2.getSort()==null?0:menu2.getSort()); //排序
        }).collect(Collectors.toList());
        return children;
    }

}